package user.zc.action;

import lombok.SneakyThrows;
import user.zc.action.comp.Action;
import user.zc.controller.IConnect;

import javax.swing.*;
import java.util.function.Consumer;

public class SelectConnectionAction extends Action<String> {

    @SneakyThrows
    public SelectConnectionAction(IConnect connectCollector, Consumer<String> callback ){
        super(callback);
        String[] names = connectCollector.connectList().toArray(new String[]{});
        JList jList = new JList<String>(names);
        JScrollPane jScrollPane = new JScrollPane(jList);
        int result = JOptionPane.showConfirmDialog(null,jScrollPane,
                "请选择一个连接",
                JOptionPane.PLAIN_MESSAGE);
        if (result == JOptionPane.YES_OPTION) {
            //需要打开连接，并且判断是否成功
            boolean isConnectedOk = false;
            try {
                isConnectedOk = connectCollector.switchConnections(jList.getSelectedValue().toString());
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null,
                        "连接失败", "连接失败", JOptionPane.ERROR_MESSAGE);
            }
            if(isConnectedOk){
                JOptionPane.showMessageDialog(null,
                        "连接成功", "连接提示", JOptionPane.INFORMATION_MESSAGE);
                call(jList.getSelectedValue().toString());
            }
        }
    }
}
